<template>
	<view class="view-page flex flex-direction" :style="skin" :class="[{ 'u-bg-white': !isResult }]">
		<view class="top-wrap">
			<zx-nav noTitle mpShowRight :bg="isResult ? '#f4f4f4' : ''">
				<view v-if="!isResult || isFocus" slot="center" class="u-text-center">搜索</view>
				<template v-else>
					<searchbar slot="center" :isSearch="true" @search="confirmSearch" v-model="searchkeyword"></searchbar>
					<view class="cart" slot="right" @tap="navTo('/pages/car/car', 'switchTab')">
						<u-badge max="99" :value="cartNum"></u-badge>
						<image :src="`${assetsPath}/cart.png`" mode="widthFix"></image>
					</view>
				</template>
			</zx-nav>
		</view>
		<template v-if="!isResult">
			<view class="tui-searchbox">
				<view class="tui-search-input">
					<icon type="search" :size="14" color="#999"></icon>
					<input
						confirm-type="search"
						:placeholder="placeholdertext"
						placeholder-class="tui-input-plholder"
						class="tui-input"
						@focus="isFocus = true"
						@blur="isFocus = false"
						v-model.trim="searchkeyword"
						@input="inputVal"
						@confirm="confirm($event)"
					/>

					<u-icon name="close-circle-fill" color="#999" size="40" @tap="cleanKey" v-if="searchkeyword"></u-icon>
				</view>
				<view v-if="!isResult || isFocus" class="tui-cancle" @tap="confirm">搜索</view>
				<navigator class="cart" v-else open-type="switchTab" url="../car/car">
					<text class="cuIcon-cart"></text>
					<view class="cu-tag badge" v-if="cartNum > 0">{{ cartNum }}</view>
				</navigator>
			</view>
			<view class="searchcontainer">
				<view class="tui-search-history" v-if="history.length > 0">
					<view class="tui-history-header">
						<view class="tui-search-title">搜索历史</view>
						<u-icon name="close-circle-fill" size="40" @tap="delHistory('all')"></u-icon>
					</view>
					<view class="tui-history-content">
						<block v-for="(item, index) in history" :key="index">
							<text class="cu-tag round" style="margin: 0 24rpx 24rpx 0" @tap="confirmSearch(item.name)" @longtap="delHistory(item.name)">{{ item.name }}</text>
						</block>
					</view>
				</view>
				<view class="tui-search-hot" v-if="hot.length > 0">
					<view class="tui-hot-header"><view class="tui-search-title">搜索发现</view></view>
					<view class="tui-hot-content">
						<block v-for="(item, index) in hot" :key="index">
							<text class="cu-tag round" style="margin: 0 24rpx 24rpx 0" @tap="confirmSearch(item.name)">{{ item.name }}</text>
						</block>
					</view>
				</view>
			</view>
		</template>
		<template v-else>
			<template v-if="pid">
				<view class="cateInfo">
					<view class="flex align-center justify-between">
						<view class="u-flex-1 flex align-center justify-start" style="min-width: 0">
							<view class="name text-cut" style="min-width: 0">{{ cateInfo.name }}</view>
							<view @tap="follow" class="btn ml22 flex align-center justify-center">
								<image src="/static/fav2.png" mode="widthFix" v-if="cateInfo.product_is_follow == 0"></image>
								<text class="ml6">{{ cateInfo.product_is_follow == 0 ? '加' : '' }}常用</text>
							</view>
						</view>
						<view class="u-primary">
							<text class="symbol">￥</text>
							<text class="price">{{ cateInfo.min_price || 0 }}</text>
							~
							<text class="price">{{ cateInfo.max_price || 0 }}</text>
						</view>
					</view>
					<view class="flex align-center justify-between mt8">
						<text class="attr margin-left-sm">
							颜色：
							<text class="u-main-color">{{ cateInfo.product_color_ }}</text>
						</text>
						<view @tap="showPriceLine" class="btn">价格走势</view>
					</view>
				</view>
			</template>
			<u-sticky :offset-top="stickyHeight"><searchfilterbar :searchkeyword="searchkeyword" @changeFilrer="changeFilrer"></searchfilterbar></u-sticky>
			<view class="flex-sub main">
				<mescroll-uni ref="mescrollItem0" :fixed="false" @init="mescrollInit" @down="downCallback" @up="upCallback" :up="upOption" :down="downOption">
					<view class="goodslist">
						<pro-item
							v-for="(items, indexs) in goodslist"
							:key="indexs"
							:proinfo="items"
							direction="row"
							:width="proWidth"
							@changeNum="info => changeInfo(info, indexs)"
							@showShootVideo="showShootVideo"
						></pro-item>
					</view>
				</mescroll-uni>
			</view>
		</template>
		<!-- 价格走势 -->
		<price-modal ref="priceModal"></price-modal>
		<sVideo ref="sVideo"></sVideo>
	</view>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js';
import searchbar from '@/components/searchbar';
import proItem from '@/components/pro-item.vue';
import searchfilterbar from '@/components/searchfilterbar.vue';
import priceModal from '@/components/priceModal';
import sVideo from '@/components/s-video/s-video';
let reg = /([^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n])|(\s)/g;

export default {
	data() {
		return {
			goodslist: [], //商品列表
			avg_price: '',
			stock_by: '',
			sales: '',
			searchkeyword: '',
			classify: '',
			pname: '请输入你想要的产品名称',
			placeholdertext: '请输入你想要的产品名称',
			pid: '',
			history: [],
			hot: [],
			isResult: false, //是否显示搜索结果
			isFocus: false,
			scrollTop: 0,
			proWidth: uni.upx2px(200) + 'px',
			downOption: {
				auto: false
			},
			upOption: {
				auto: false
			},
			cateInfo: {},
			isFixed: false,
			filter: {}
		};
	},
	components: {
		proItem,
		searchbar,
		searchfilterbar,
		priceModal,
		sVideo
	},
	mixins: [MescrollMixin],
	created() {},
	computed: {
		...mapState(['keyword', 'memberId', 'cartNum', 'CustomBar']),
		stickyHeight() {
			return this.CustomBar * (750 / uni.getSystemInfoSync().windowWidth);
		}
	},
	onShareAppMessage(res) {
		let shareUrl = '/pages/search/search?pname=' + this.searchkeyword;
		if (this.pid) {
			shareUrl += '&pid=' + this.pid;
		}
		if (this.memberId) {
			shareUrl += '&recommenderId=' + this.memberId;
		}
		return {
			title: this.searchkeyword,
			path: shareUrl
			// imageUrl: this.share_img
		};
	},
	onShareTimeline() {
		let shareUrl = '/pages/search/search?pname=' + this.searchkeyword;
		if (this.pid) {
			shareUrl += '&pid=' + this.pid;
		}
		if (this.memberId) {
			shareUrl += '&recommenderId=' + this.memberId;
		}
		return {
			title: this.searchkeyword,
			path: shareUrl
			// imageUrl: this.share_img
		};
	},
	onLoad(option) {
		this.placeholdertext = option.placeholdertext || '请输入你想要的产品名称';
		if (option.pname) {
			this.pname = option.pname;
			this.searchkeyword = option.pname;
			this.pid = option.pid;
			if (this.pid) {
				this.getCateInfo();
			}
			this.isResult = true;
			this.$nextTick(() => {
				if (this.mescroll) {
					this.mescroll.resetUpScroll();
				}
			});
		} else {
			this.searchkeyword = '';
			this.pid = '';
			this.isResult = false;
			this.getHistory();
		}
		// this.SET_KEYWORD('');
	},
	methods: {
		...mapMutations(['SET_KEYWORD']),
		/*下拉刷新的回调, 有三种处理方式: */
		downCallback() {
			this.mescroll.resetUpScroll(); // 重置列表为第一页 (自动执行 page.num=1, 再触发upCallback方法 )
		},
		/*上拉加载的回调*/
		upCallback(mescroll) {
			this.getProductList();
		},
		inputVal(e) {
			let val = e.detail.value;
			if (val.match(reg)) {
				val = val.replace(reg, '');
				this.$nextTick(() => {
					this.searchkeyword = val;
				});
			}
		},
		/* 获取产品 */
		getProductList() {
			let $me = this;
			let pageNum = this.mescroll.num; // 页码, 默认从1开始
			let pageSize = this.mescroll.size;
			let param = {
				page: pageNum,
				limit: pageSize,
				...this.filter
			};
			if (pageNum == 1) {
				$me.goodslist = [];
			}

			if (this.pid) {
				param.product_id = this.pid;
			} else if (this.searchkeyword) {
				param.name = this.searchkeyword;
			}
			this.$postAction(this.$api.getProductList, param)
				.then(da => {
					if (da.code == 0 && da.data && da.data.length > 0) {
						let curPageData = da.data;
						$me.mescroll.endBySize(curPageData.length, da.count);
						if ($me.mescroll.num == 1) $me.goodslist = []; //如果是第一页需手动制空列表
						$me.goodslist = $me.goodslist.concat(curPageData); //追加新数据
					} else {
						$me.goodslist = [];
						$me.mescroll.endSuccess(0, false);
					}
				})
				.catch(() => {
					//联网失败, 结束加载
					this.mescroll.endErr();
				});
		},
		getCateInfo() {
			this.$postAction(this.$api.getProductTypeList, {
				id: this.pid
			})
				.then(da => {
					if (da.code == 0 && da.data && da.data.length > 0) {
						this.cateInfo = da.data[0];
					} else {
					}
				})
				.catch(() => {
					//联网失败, 结束加载
					this.mescroll.endErr();
				});
		},

		cleanKey() {
			this.searchkeyword = '';
		},
		/* 获取查询历史 */
		getHistory() {
			this.$postAction(this.$api.searchRecord).then(da => {
				this.hot = da.data.guess_like;
				this.history = da.data.user_search;
			});
		},
		/* 确认搜索 */
		confirmSearch(searchkeyword) {
			this.searchkeyword = searchkeyword;
			this.confirm();
		},
		confirm() {
			if (this.searchkeyword == '' && this.placeholdertext != '请输入你想要的产品名称') {
				this.searchkeyword = this.placeholdertext;
			}
			this.isResult = true;
			this.pid = '';
			this.pname = '';
			this.isResult = true;
			this.$nextTick(() => {
				this.mescroll.resetUpScroll();
			});
		},
		delHistory(name) {
			var $me = this;
			uni.showModal({
				title: '提示',
				content: '你确定要删除吗',
				success: function (res) {
					if (res.confirm) {
						let param = {};
						if (name == 'all') {
							param.all = 1;
						} else {
							param.name = name;
						}
						$me.$postAction($me.$api.delSearchRecord, param).then(da => {
							if (da.code == 0) {
								if (name == 'all') {
									$me.history = [];
								} else {
									$me.history = $me.history.filter(item => item.name != name);
								}
							}
						});
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		},
		showPriceLine() {
			this.$refs.priceModal.show({
				id: this.pid,
				name: this.pname
			});
		},
		follow() {
			let url = this.cateInfo.product_is_follow ? this.$api.delFollow : this.$api.addFollow;
			this.$postAction(url + this.cateInfo.id + '/3', null, {
				custom: {
					ShowLoading: false
				}
			}).then(da => {
				if (da.code == 0) {
					this.cateInfo.product_is_follow = this.cateInfo.product_is_follow == 1 ? 0 : 1;
					uni.showToast({
						title: this.cateInfo.product_is_follow ? '已设常用' : '已取消常用',
						icon: 'none'
					});
				}
			});
		},
		changeInfo(info, index) {
			this.$set(this.goodslist, index, info);
		},
		navTo(url, type) {
			uni[type]({
				url: url
			});
		},
		changeFilrer(filter) {
			this.filter = { ...filter };
			this.downCallback();
		},
		showShootVideo(info) {
			this.$refs.sVideo.show(info);
		}
	}
};
</script>

<style lang="scss">
.cart {
	position: relative;
	image {
		display: block;
		width: 46upx;
		height: 43upx;
	}
	.u-badge {
		position: absolute;
		right: 0rpx;
		transform: translate(50%, -50%);
		top: 0;
		z-index: 999;
	}
}
page,
.view-page {
	height: 100%;
	overflow: hidden;
	position: relative;
}

.main {
	overflow: auto;
	background: #fff;
	margin: 0;
	-webkit-overflow-scrolling: touch;
}
.cateInfo {
	padding: 0 30rpx 20rpx;
	color: #353535;
	.attr {
		color: #636366;
		font-size: 26upx;
	}
	.name {
		font-size: 36rpx;
		font-weight: bold;
		color: #000;
	}
	.symbol {
		font-size: 28rpx;
		font-weight: 500;
	}
	.price {
		font-size: 44rpx;
		font-weight: 500;
	}
	.num {
		font-size: 36rpx;
		color: #c3140f;
	}
	.btn {
		color: #1c1c1e;
		border-radius: 50rpx;
		background: #fff;
		width: 160rpx;
		line-height: 48rpx;
		text-align: center;
		border: 1px solid #dbdbdb;
		font-size: 24upx;
		image {
			display: block;
			width: 26upx;
			height: 26upx;
		}
	}
}

.goodslist {
	margin: 0 28upx 0;
}
.tui-searchbox {
	margin: 0 30rpx;
	padding: 30rpx 0;
	box-sizing: border-box;
	display: flex;
	align-items: center;
}

.tui-search-input {
	width: 100%;
	height: 72rpx;
	border-radius: 40rpx;
	padding: 0 30rpx;
	margin-right: 10rpx;
	box-sizing: border-box;
	background: #efefef;
	display: flex;
	align-items: center;
	flex-wrap: nowrap;
}

.tui-input {
	flex: 1;
	color: #333;
	padding: 0 16rpx;
	font-size: 28rpx;
}

.tui-input-plholder {
	font-size: 28rpx;
	color: #b2b2b2;
}

.tui-cancle {
	color: #333;
	font-size: 28rpx;
	padding-left: 30rpx;
	font-weight: bold;
	flex-shrink: 0;
}
.searchcontainer {
	padding: 0 30rpx 30rpx 30rpx;
	box-sizing: border-box;
}
.tui-history-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 30rpx 0;
}
.tui-history-content,
.tui-hot-content {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	.cu-tag {
		background: #efefef;
		border-radius: 27upx;
		display: flex;
		padding: 10upx 27upx;
		color: #1c1c1e;
		font-size: 24upx;
	}
}

.tui-icon-delete {
	padding: 10rpx;
	font-size: 28rpx;
	color: #333;
}

.tui-search-title {
	font-size: 28rpx;
	font-weight: bold;
}

.tui-hot-header {
	padding: 30rpx 0;
}

.tui-header {
	padding: 26rpx 0;
	box-sizing: border-box;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.tui-header-left {
	font-size: 30rpx;
	color: #222;
	border-left: 4rpx solid #eb0909;
	padding-left: 10rpx;
	word-break: break-all;
}

.tui-noboredr {
	border-left: 0 !important;
}

.tui-result-box {
	font-size: 28rpx;
}

.tui-result-item {
	line-height: 28rpx;
	padding: 28rpx 0;
}
</style>
